package com.qpf

def file = new File("File_.groovy")

println("file ${file.name} in ${file.absolutePath} size is ${file.length()} bytes")
println("=============================")
file.eachLine { line ->
    println(line)
}
println("=============================")

tmp = '../../../tmp'

def bak = new File(tmp)

if (!bak.exists()) {
    bak.mkdirs()
}

bak = new File(bak, file.name)

bak.createNewFile()

bak.withWriter {writer ->
    file.readLines().each {
        line -> writer.append("${line}\n")
    }
}

class Person implements Serializable{
    java.lang.String name
    Integer age
    void display() {
        println("Person: name: ${getName()}, age: ${getAge()}")
    }
}

def person = new Person(name: 'sdl', age: 27)
person.display()
writeObject(person, "${tmp}/stu.bin")
def person_ = readObject("${tmp}/stu.bin")
person_.display()

def readObject(path) {
    def result
    try {
        def file = new File(path)
        if (file == null || !file.exists()) return null
        file.withObjectInputStream {
            input -> result = input.readObject()
        }
    } catch (Exception e) {
        println("ERROR: ${e.getMessage()}")
    }
    return result
}
def writeObject(obj, path) {
    try {
        def file = new File(path)
        if (!file.exists()) {
            file.createNewFile()
        }
        file.withObjectOutputStream {
            out -> out.writeObject(obj)
        }
    } catch (Exception e) {
        println("ERROR: ${e.getMessage()}")
    }
}